// stores/bluetooth.ts
import { defineStore } from 'pinia'

interface BluetoothDevice {
	deviceId : string
	name : string
	localName ?: string
	aliasName ?: string
	connected : boolean
	connectedAt ?: number
	config ?: any
	notifying ?: boolean
}

interface BluetoothState {
	adapterOpen : boolean
	adapterState : any
	devices : BluetoothDevice[]
	connectedDevices : Record<string, BluetoothDevice>
	messages : Record<string, any[]>
}

export const useBluetoothStore = defineStore('bluetooth', {
	state: () : BluetoothState => ({
		adapterOpen: false,
		adapterState: {}, // 蓝牙适配器-- 可用状态-available、扫描状态-discovering
		devices: [],
		connectedDevices: {},
		messages: {}
	}),

	getters: {
		getConnectedDevices: (state) => {
			return Object.values(state.connectedDevices).sort((a, b) => {
				if (a.connected && !b.connected) return -1
				if (!a.connected && b.connected) return 1
				return 0
			})
		}
	},

	actions: {
		initStore() {
			// 初始化时从本地存储加载已连接设备
			try {
				const stored = uni.getStorageSync('connectedDevices')
				if (stored) {
					this.connectedDevices = JSON.parse(stored)
				}
			} catch (error) {
				console.warn('加载蓝牙设备缓存失败:', error)
			}
		},

		setAdapterOpen(val : boolean) {
			this.adapterOpen = val
		},

		setAdapterState(val : any) {
			this.adapterState = val
		},

		clearDevices() {
			this.devices = []
		},

		addDevice(dev : BluetoothDevice) {
			// 避免重复添加
			if (!this.devices.find(d => d.deviceId === dev.deviceId)) {
				this.devices.push(dev)
			}
		},

		addConnectedDevice(dev : BluetoothDevice) {
			this.connectedDevices[dev.deviceId] = dev
			// this.saveConnectedDevices()
		},

		removeConnectedDevice(deviceId : string) {
			delete this.connectedDevices[deviceId]
			// this.saveConnectedDevices()
		},

		updateConnection(payload : { deviceId : string; connected : boolean }) {
			const { deviceId, connected } = payload
			if (this.connectedDevices[deviceId]) {
				this.connectedDevices[deviceId].connected = connected
				// this.saveConnectedDevices()
			}
		},

		updateDeviceAlias(payload : { deviceId : string; aliasName : string }) {
			const { deviceId, aliasName } = payload
			if (this.connectedDevices[deviceId]) {
				this.connectedDevices[deviceId].aliasName = aliasName
			}

			// 同时更新设备列表中的别名
			const device = this.devices.find(d => d.deviceId === deviceId)
			if (device) {
				device.aliasName = aliasName
			}

			// this.saveConnectedDevices()
		},

		addMessage(payload : { deviceId : string; data : any }) {
			const { deviceId, data } = payload
			if (!this.messages[deviceId]) {
				this.messages[deviceId] = []
			}
			this.messages[deviceId].push(data)
		},

		saveConnectedDevices() {
			uni.setStorageSync('connectedDevices', JSON.stringify(this.connectedDevices))
		}
	},

	persist: {
		key: 'bluetooth-store',
		paths: [
			// 可以选择需要持久化的状态
			"connectedDevices"
		]
	}
})